package com.hk.commons.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;


/**
 * @author Kevin
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class UrlUtils {

    private static final Pattern ABSOLUTE_URL = Pattern.compile("\\A[a-z0-9.+-]+://.*", Pattern.CASE_INSENSITIVE);

    public static String urlEncode(final String value) {
        return urlEncode(value, StandardCharsets.UTF_8.name());
    }

    @SneakyThrows(value = {UnsupportedEncodingException.class})
    public static String urlEncode(final String value, final String encoding) {
        return URLEncoder.encode(value, encoding);
    }

    public static String urlDecoder(final String value) {
        return urlDecoder(value, StandardCharsets.UTF_8.name());
    }

    @SneakyThrows(value = {UnsupportedEncodingException.class})
    public static String urlDecoder(final String value, final String encoding) {
        return URLDecoder.decode(value, encoding);
    }

    public static boolean isAbsoluteUrl(String url) {
        return StringUtils.hasLength(url) && ABSOLUTE_URL.matcher(url).matches();
    }
}
